<?php

/**
 * Created by IntelliJ IDEA.
 * User: andyhuang
 * Date: 2018/3/18
 * Time: 16:46
 */
define("DB_HOST", "localhost:3306");
define("DB_USER", "root");
define("DB_PASS", "Welcome1");
define("DB_NAME", "WeChat");

$connt = null;

function isExistCurrentOpenId($openid){
    $sql = "SELECT Customer_ID FROM Customer_Details WHERE Open_ID = '".$openid."';";
    $retval = exeSqlCmd($sql);
    if(!$retval)
    {
        return false;
    }
    $row = mysql_fetch_array($retval, MYSQL_NUM);
    return $row;

}


function getProductsByOpenid($openid) {
    if(!empty($_SESSION["current_productIds"])){
        return getProductsByProductIds($_SESSION["current_productIds"]);
    }
    $isExisted = isExistCurrentOpenId($openid);
    //var_dump($isExisted);
    $productIds = array();
    if($isExisted) {
        $sql = getSelectProductsSql($openid);
        $retval = exeSqlCmd($sql);
        $products = translateProductMysqlArray($retval);
    }else{
        $products =  getRandomProducts();
    }
    foreach($products as $product){
        array_push($productIds, $product["productId"]);
    }
    if(count($productIds) > 0) {
        $_SESSION["current_productIds"] = $productIds;
    }

    return $products;
}

function translateProductMysqlArray($retval) {
    $result = array();
    if(! $retval )
    {
        return $result;
    }

    while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
    {
        if(empty($row['Product_ID'])){
            continue;
        }
        array_push($result,[
            'productId' => $row['Product_ID'],
            'productName' => $row["Product_Name"],
            'productUrl' => $row["Product_URL"],
            'price' => $row["Price"],
            'cateId' => $row["Cata_ID"],
            'productPicURL' => $row["Product_Pic_URL"]
        ]);
    }
    return $result;
}

function exeSqlCmd($sql) {
    $conn = connnectToDB();
    if(!$conn){
        return null;
    }
    mysql_select_db( DB_NAME, $conn);
    $retval = mysql_query( $sql,$conn);
    if(! $retval )
    {
        die("无法读取数据:$sql, " . mysql_error($conn));
        return null;
    }
    return $retval;
}

function getSelectProductsSql($openid) {
    $sqlArray = array();
    for($i = 1; $i < 9; $i++) {
        $temp = "select c1.* from Customer_Details a".
            " LEFT JOIN uDecide_out b".
            " on a.Customer_ID = b.Customer_ID".
            " LEFT JOIN Product_Details c1".
            " on b.Product_ID_$i = c1.Product_ID".
            " where a.Open_ID = '$openid'";
        $sqlArray[] = $temp;
    }
    //var_dump(join(" union ALL ", $sqlArray));
    return join(" union ALL ", $sqlArray);
}

function getRandomProducts() {
    $products = array();
    for($i = 1; $i < 9; $i++) {
        $productsOfSameCate = getProductsByCateId($i);
        $index = mt_rand(0,count($productsOfSameCate)-1);
        if(!empty($productsOfSameCate[$index])){
            array_push($products,$productsOfSameCate[$index]);
        }
    }
    return $products;
}

function connnectToDB() {
    global $connt;
    if($connt){
        return $connt;
    }
    $connt = mysql_connect(DB_HOST, DB_USER, DB_PASS);
    if(! $connt )
    {
        $connt = null;
        die('不能连接数据库: ' . mysql_error());
    }
    return $connt;

}


function closeDB() {
    global $connt;
    if ($connt) {
        mysql_close($connt);
        $connt = null;
    }
}

function getProductsByCateId($cateId) {
    $sql = "SELECT * from Product_Details WHERE Cata_ID = $cateId";
    $retval = exeSqlCmd($sql);
    $products = translateProductMysqlArray($retval);
    return $products;
}

function getProductsByProductIds($productIds) {
    $sql = "SELECT * from Product_Details WHERE Product_ID IN (".join(',',$productIds).")";
    $retval = exeSqlCmd($sql);
    $products = translateProductMysqlArray($retval);
    return $products;
}
